//
//  SLProductInfoViewController.m
//  SecondLoan
//
//  Created by Echo Zhangjie on 2019/8/20.
//  Copyright © 2019 姚永波. All rights reserved.
//

#import "SLProductInfoViewController.h"
#import "SLProductTitleView.h"
#import "SLContractView.h"
#import "ProductDetailModel.h"
#import "NSString+JXCommon.h"
#import "IDCardViewController.h"
#import "SLApplyLoacnViewController.h"
#import "SLVerifySubmitViewController.h"
#import "LoginController.h"
#import "SLEditInfoViewController.h"
#import "SLVerifyFailedViewController.h"
#import "SLVerifyViewController.h"
#import "ProductTopView.h"
#import "UIImage+Stretch.h"
#import "PDWebViewController.h"
#import "WKBGlobalData.h"
#import "NSString+Tools.h"
#import "MyMoneyRangeModel.h"

@interface SLProductInfoViewController()<SLContractViewDelegate>

@property (strong, nonatomic) UIImageView *imgTopProduct;

@property (strong, nonatomic) ProductTopView *productTopView;

@property (strong, nonatomic) SLProductTitleView *procedureTitle;
@property (strong, nonatomic) UIImageView *procedure; //申请流程

@property (strong, nonatomic) SLProductTitleView *conditionTitle;
@property (strong, nonatomic) UILabel *lblConditionContent;

@property (strong, nonatomic) SLProductTitleView *prepareTitle;
@property (strong, nonatomic) UILabel *lblPrepareContent;


@property (strong, nonatomic) SLContractView *contractView;
@property (strong, nonatomic) UIButton *btnApply;

@property (strong, nonatomic) ProductDetailModel *model;

@end

@implementation SLProductInfoViewController


- (void)setupView{
  self.view.develop(^(FFactory * factory){
      factory.scrollView().fsBackGroundColor(0xFFFFFF).develop(^(FFactory * factory){
          
          factory.cView([ProductTopView newView]).fsFvid(@"productDetail");
          
          factory.view().fsBackGroundColor(0xFFFFFF).develop(^(FFactory * factory){
              factory.cView([SLProductTitleView newView]).fsFvid(@"applyTitle");
              factory.imageView().fsClip(YES).fsFvid(@"applyView");
          }).fsFvid(@"productApplySteps");
          
          factory.view().fsBackGroundColor(0xFFFFFF).develop(^(FFactory * factory){
              factory.cView([SLProductTitleView newView]).fsFvid(@"conditionTitle");
              factory.label().fsText(@"申请条件").fsTextColor(0x666666).fsFont(Font14).fsLines(0).fsFvid(@"conditionContent");
          }).fsFvid(@"condition");
          
          factory.view().fsBackGroundColor(0xFFFFFF).develop(^(FFactory * factory){
              factory.cView([SLProductTitleView newView]).fsFvid(@"prepareTitle");
              factory.label().fsText(@"准备资料").fsTextColor(0x666666).fsFont(Font14).fsLines(0).fsFvid(@"prepareContent");
        factory.label().fsText(@"温馨提示普惠快贷申办时间：9：00-17：00").fsTextColor(0x666666).fsFont(Font14).fsLines(0).fsFvid(@"lblInfo");
              
          }).fsFvid(@"prepare");

        
          
      }).fsFvid(@"contain");
      
      factory.view().fsBackGroundColor(0xFFFFFF).develop(^(FFactory * factory){
          factory.cView([SLContractView newView]).fsFvid(@"contractView");
          factory.button().fsText(@"我要申请").fsFont(Font18Bold).fsBackGroundImage(@"btn_red_yellow").fsTextColor(0xFFFFFF).fsOnClick(applyBtnDidClick:).fsFvid(@"applyBtn");
      }).fsFvid(@"apply");
  });


  [fQuery(self.view, @"productDetail") mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(fQuery(self.view, @"contain"));
    make.centerX.equalTo(fQuery(self.view, @"contain"));
    make.width.equalTo(fQuery(self.view, @"contain"));
    make.height.equalTo(@270);
  }];
  [fQuery(self.view, @"productApplySteps") mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(fQuery(self.view, @"productDetail").mas_bottom);
    make.centerX.equalTo(self.view);
    make.width.equalTo(self.view);
    make.height.equalTo(@100);
  }];

  [fQuery(self.view, @"applyTitle") mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(fQuery(self.view, @"productApplySteps").mas_top);
    make.left.equalTo(fQuery(self.view, @"productApplySteps"));
    make.height.equalTo(@30);
  }];
    
  [fQuery(self.view, @"applyView") mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(fQuery(self.view, @"applyTitle").mas_bottom).with.mas_offset(10);
    make.left.equalTo(fQuery(self.view, @"productApplySteps")).with.mas_offset(20);
    make.right.equalTo(fQuery(self.view, @"productApplySteps")).with.mas_offset(-20);
    make.height.equalTo(@50);
  }];
    
    [fQuery(self.view, @"condition") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fQuery(self.view, @"applyView").mas_bottom);
        make.centerX.equalTo(self.view);
        make.width.equalTo(self.view);
        make.height.equalTo(@100);
    }];
    
    [fQuery(self.view, @"conditionTitle") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fQuery(self.view, @"condition").mas_top).mas_offset(10);
        make.left.equalTo(fQuery(self.view, @"condition"));
        make.height.equalTo(@30);
    }];
    
    [fQuery(self.view, @"conditionContent") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fQuery(self.view, @"conditionTitle").mas_bottom).with.mas_offset(10);
        make.left.equalTo(fQuery(self.view, @"condition")).with.mas_offset(10);
        make.right.equalTo(fQuery(self.view, @"condition")).with.mas_offset(-10);
        make.height.equalTo(@70);
    }];
    
    [fQuery(self.view, @"prepare") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fQuery(self.view, @"condition").mas_bottom);
        make.centerX.equalTo(self.view);
        make.width.equalTo(self.view);
        make.height.equalTo(@100);
    }];
    [fQuery(self.view, @"prepareTitle") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fQuery(self.view, @"prepare").mas_top);
        make.left.equalTo(fQuery(self.view, @"prepare"));
        make.height.equalTo(@30);
    }];
    
    [fQuery(self.view, @"prepareContent") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fQuery(self.view, @"prepareTitle").mas_bottom).with.mas_offset(10);
        make.left.equalTo(fQuery(self.view, @"prepare")).with.mas_offset(10);
        make.right.equalTo(fQuery(self.view, @"prepare")).with.mas_offset(-10);
        make.height.equalTo(@40);
    }];
    [fQuery(self.view, @"lblInfo") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fQuery(self.view, @"prepareContent").mas_bottom).with.mas_offset(10);
        make.left.equalTo(fQuery(self.view, @"prepare")).with.mas_offset(10);
        make.right.equalTo(fQuery(self.view, @"prepare")).with.mas_offset(-10);
        make.height.equalTo(@20);
    }];
    
    [fQuery(self.view, @"apply") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).with.mas_offset(- KMagrinBottom);
        make.centerX.equalTo(self.view);
        make.width.equalTo(self.view);
        make.height.equalTo(@90);
    }];
    [fQuery(self.view, @"contractView") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fQuery(self.view, @"apply").mas_top);
        make.centerX.equalTo(fQuery(self.view, @"apply"));
        make.right.equalTo(fQuery(self.view, @"apply")).with.mas_offset(-10);
        make.height.equalTo(@30);
    }];
  [fQuery(self.view, @"applyBtn") mas_makeConstraints:^(MASConstraintMaker *make) {
      make.top.equalTo(fQuery(self.view, @"contractView").mas_bottom);
    make.left.equalTo(fQuery(self.view, @"apply")).with.mas_offset(10);
    make.right.equalTo(fQuery(self.view, @"apply")).with.mas_offset(-10);
    make.height.equalTo(@50);
  }];
//    self.imgTopProduct = fQueryImgv(self.view, @"productAD");
    self.productTopView  = (ProductTopView *)fQuery(self.view, @"productDetail");
    self.procedureTitle = (SLProductTitleView *)fQuery(self.view, @"applyTitle");
    self.procedureTitle.title.text = @"申请流程";
    self.procedure = (UIImageView *)fQuery(self.view, @"applyView");
    self.procedure.contentMode = UIViewContentModeScaleToFill;

    self.conditionTitle = (SLProductTitleView *)fQuery(self.view, @"conditionTitle");
    self.conditionTitle.title.text = @"申请条件";
    self.lblConditionContent = fQueryLbl(self.view, @"conditionContent");
    
    self.prepareTitle = (SLProductTitleView *)fQuery(self.view, @"prepareTitle");
    self.prepareTitle.title.text = @"准备资料";
    self.lblPrepareContent = fQueryLbl(self.view, @"prepareContent");
    
    self.contractView = (SLContractView *)fQuery(self.view, @"contractView");

    self.btnApply = (UIButton *)fQueryBtn(self.view, @"applyBtn");
    self.btnApply.layer.cornerRadius = 8;
    self.btnApply.layer.masksToBounds = YES;
    [self.btnApply setBackgroundImage:[UIImage createImageWithColor:COLOR_Gary_F3] forState:UIControlStateDisabled];
    self.btnApply.enabled = NO;
    self.contractView.delegate = self;
    
    [fQueryScroll(self.view, @"contain") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.mas_equalTo(self.view.mas_bottom).with.mas_offset(-90);
    }];
    fQueryScroll(self.view, @"contain").bounces = NO;
    self.view.backgroundColor = COLOR_White;
    if (self.isPuhui) {
        fQuery(self.view, @"lblInfo").hidden = NO;
    }else{
        fQuery(self.view, @"lblInfo").hidden = YES;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupView];
    // Do any additional setup after loading the view from its nib.
    [self loadData];
    fQueryScroll(self.view, @"contain").contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT * 1.25 - 64);
}



- (void)updateView{
    fQueryScroll(self.view, @"contain").contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
    if (self.isPuhui) {
        self.productTopView.lblHintRate.text = @"年利率";
    }
    // 计算申请条件和准备资料的高度
    if (self.model.condition) {
        CGSize size = [self.model.condition getSizeWithFont:Font14 constrainedToSize:CGSizeMake(SCREEN_WIDTH - 2*10, SCREEN_HEIGHT)];
        [self.lblConditionContent mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(fQuery(self.view, @"conditionTitle").mas_bottom).with.mas_offset(10);
            make.left.equalTo(fQuery(self.view, @"condition")).with.mas_offset(10);
            make.right.equalTo(fQuery(self.view, @"condition")).with.mas_offset(-10);
            make.height.equalTo(@(size.height + 10));
        }];
        [fQuery(self.view, @"condition") mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(fQuery(self.view, @"applyView").mas_bottom);
            make.centerX.equalTo(self.view);
            make.width.equalTo(self.view);
            make.height.equalTo(@(size.height + 70));
        }];
    }
    if (self.model.preInfo) {
        CGSize size = [self.model.preInfo getSizeWithFont:Font14 constrainedToSize:CGSizeMake(SCREEN_WIDTH - 2*10, SCREEN_HEIGHT)];
        [self.lblPrepareContent mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(fQuery(self.view, @"prepareTitle").mas_bottom).with.mas_offset(10);
            make.left.equalTo(fQuery(self.view, @"prepare")).with.mas_offset(10);
            make.right.equalTo(fQuery(self.view, @"prepare")).with.mas_offset(-10);
            make.height.equalTo(@(size.height + 10));
        }];
        [fQuery(self.view, @"prepare") mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(fQuery(self.view, @"condition").mas_bottom);
            make.centerX.equalTo(self.view);
            make.width.equalTo(self.view);
            make.height.equalTo(@(size.height + 90));
        }];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginUpdateView) name:NOTIFICATION_LOGINSUCCESS object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)loginUpdateView{
    if (self.isPuhui) {
        WKBPopToRooterViewController();
    }else{
        
    }
//    NSMutableDictionary * param = [NSMutableDictionary dictionary];
//    [param setObject:[UserLocal token] forKey:@"token"];
//    [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_my_quota) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
//        [self HUDdismiss];
//        if (!error) {
//            MyMoneyRangeModel *model  = [MyMoneyRangeModel mj_objectWithKeyValues:responseObject[@"data"]];
//            [WKBGlobalData shareManager].homeMoneyModel = model;
//            if (model && model.status == CodeCreditPassed) { //
//                WKBPopToRooterViewController();
//            }
//        }
//    }];
}
- (void)loadData
{
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    [param setObject:[UserLocal token] forKey:@"token"];
    [param setObject:self.productId forKey:@"productId"];
    [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_product_info) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
        if (!error) {
            self.model = [ProductDetailModel mj_objectWithKeyValues:responseObject[@"data"]];
            self.productTopView.model = self.model;
            [self.procedure sd_setImageWithURL:[NSURL URLWithString:self.model.applyProcess] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                if (image!=nil) {
                    [fQuery(self.view, @"applyView") mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.top.equalTo(fQuery(self.view, @"applyTitle").mas_bottom).with.mas_offset(10);
                        make.left.equalTo(fQuery(self.view, @"productApplySteps")).with.mas_offset(20);
                        make.right.equalTo(fQuery(self.view, @"productApplySteps")).with.mas_offset(-20);
                        make.height.equalTo(@((SCREEN_WIDTH-40)*image.size.height/image.size.width));
                    }];
                }
            }];
            self.lblConditionContent.text = self.model.condition;
            self.lblPrepareContent.text = self.model.preInfo;
            [self updateView];
        } else {
            [self HUDshowErrorWithStatus:error.localizedDescription];
        }
    }];
}

#pragma mark ==== SLContractViewDelegate ======
- (void)acceptContract:(UIButton *)btn{
    self.btnApply.enabled = btn.isSelected;
}
- (void)clickPrivate2Contract{
    PDWebViewController * vc = [[PDWebViewController alloc] init];
    vc.webUrl =  url_private_polity;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)clickPrivate1Contract{
    PDWebViewController * vc = [[PDWebViewController alloc] init];
    vc.webUrl =  url_private_protocal;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)applyBtnDidClick:(UIButton *)sender {
    
  if (!self.contractView.acceptBtn.isSelected) {
    [self HUDshowErrorWithStatus:@"请阅读并接受贷款协议"];
    return;
  }
    if ([UserLocal isLogin]) { // 登录 --
//        sender.enabled = NO;
        if (self.isPuhui) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"借款人应严格按照所申请的用途使用信贷资金，不得用于证券市场和期货市场、不得用于购房和房地产项目开发、不得用于购买理财产品、债券及投资账户交易类产品，不得用于股本权益性投资，不得用于借贷、套利，不得用于洗钱等国家法律法规明确规定不得经营的项目" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                sender.enabled = NO;
                NSMutableDictionary * param = [NSMutableDictionary dictionary];
                [param setObject:[UserLocal token] forKey:@"token"];
                [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_loan_apply_puhui) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
                    //                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    sender.enabled = YES;
                    //                });
                    //        [self HUDdismiss];
                    NSInteger state = [responseObject[@"status"] integerValue] ;
                    if (state == CodePuhuiLoanVerify) {
                        IDCardViewController *cardVC = [[IDCardViewController alloc] initWithNibName:@"IDCardViewController" bundle:nil];
                        cardVC.isForPuhuiProduct = self.isPuhui;
                        cardVC.productId = self.productId;
                        cardVC.isOnlyAuth = NO;
                        [self.navigationController pushViewController:cardVC animated:YES];
                    }else if (state == CodePuhuiLoanNeedInfo){
                        SLEditInfoViewController *editVC = [[SLEditInfoViewController alloc] init];
                        [self.navigationController pushViewController:editVC animated:YES];
                    }else if(state == CodePuhuiLoanPassed){
                        SLVerifySubmitViewController *vc = [[SLVerifySubmitViewController alloc] initWithNibName:@"SLVerifySubmitViewController" bundle:nil];
                        vc.isPuhui = YES;
                        [self.navigationController pushViewController:vc animated:YES];
                    }else if (state == CodePuhuiLoanFailed){
                        [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_my_quota) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
                            [self HUDdismiss];
                            MyMoneyRangeModel *myMoneyRange = [MyMoneyRangeModel mj_objectWithKeyValues:responseObject[@"data"]];
                            [WKBGlobalData shareManager].homeMoneyModel = myMoneyRange;
                            if (myMoneyRange && myMoneyRange.status == CodeCreditPassed) { //
                                SLVerifyViewController *vcController = [[SLVerifyViewController alloc] init];
                                vcController.money = [NSString stringWithFormat:@"%@",[NSString getMoneyStringWithMoneyNumber:myMoneyRange.viewQuota]];
                                [self.navigationController pushViewController:vcController animated:YES];
                            }
                        }];
                    }else if (state == CodePuhuiLoanNotTime){
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"温馨提示普惠快贷申办时间：9：00-17：00"
                                                                      delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
                        [alert show];
                    }else if(state == 200){
                        SLVerifySubmitViewController *vc = [[SLVerifySubmitViewController alloc] initWithNibName:@"SLVerifySubmitViewController" bundle:nil];
                        vc.isPuhui = YES;
                        [self.navigationController pushViewController:vc animated:YES];
                    }else{
                        [self HUDshowErrorWithStatus:responseObject[@"msg"]];
                    }
                    //                if (!error) {
                    //
                    //                } else {
                    //                    [self HUDshowErrorWithStatus:error.localizedDescription];
                    //                }
                }];
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:okAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }else{
            sender.enabled = NO;
            NSMutableDictionary * param = [NSMutableDictionary dictionary];
            [param setObject:[UserLocal token] forKey:@"token"];
            [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_get_auth) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
                [self HUDdismiss];
                sender.enabled = YES;
                if (!error) {
                    BOOL isAuth = NO;
                    if ([responseObject[@"data"] integerValue] == CodeVerifyPassed){
                        isAuth = YES;
                    }
                    if (isAuth) { // 如果认证成功，先调用贷款申请获取状态
                        SLApplyLoacnViewController *applyVC = [[SLApplyLoacnViewController alloc] init];
                        applyVC.productId = self.productId;
                        [self.navigationController pushViewController:applyVC animated:YES];
                    }else{
                        IDCardViewController *cardVC = [[IDCardViewController alloc] initWithNibName:@"IDCardViewController" bundle:nil];
                        //                        cardVC.isForPuhuiProduct = self.isPuhui;
                        cardVC.productId = self.productId;
                        cardVC.isOnlyAuth = NO;
                        [self.navigationController pushViewController:cardVC animated:YES];
                    }
                }else {
                    [self HUDshowErrorWithStatus:error.localizedDescription];
                }
            }];
        }
    }else{
        MainNavigationController *vc = [[MainNavigationController alloc]initWithRootViewController:[[LoginController alloc] init]];
        [self presentViewController:vc animated:YES completion:nil];
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
